package com.pan.kang.impl.service;

import com.pan.kang.domain.po.EmployPO;
import com.pan.kang.domain.vo.CommonVO;
import com.pan.kang.framework.GeneralContext;
import com.pan.kang.framework.Transfer;
import com.pan.kang.repositories.EmployRepository;
import com.pan.kang.service.IEmployService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.*;

@Service
public class EmployService extends GeneralContext<EmployPO, String, EmployRepository>
        implements IEmployService {


    public Page<CommonVO> queryEmployPage(EmployPO employPO, int limit, int offset) {
        PageRequest pageRequest = PageRequest.of(offset,
                limit);
        Specification<EmployPO> spec = (root, criteriaQuery, criteriaBuilder) -> {
            final List<Predicate> predicates = new ArrayList<Predicate>();
            if (!StringUtils.isEmpty(employPO.getName())) {
                Expression<String> exp = root.get("name");
                predicates.add(criteriaBuilder.like(exp, "%" + employPO.getName() + "%"));
            }
            if (!StringUtils.isEmpty(employPO.getSex())) {
                predicates.add(criteriaBuilder.equal(root.get("sex"), employPO.getSex()));
            }
            if (!StringUtils.isEmpty(employPO.getBirthday())) {
                predicates.add(criteriaBuilder.equal(root.get("birthday"), employPO.getBirthday()));
            }
            if (!StringUtils.isEmpty(employPO.getEmail())) {
                predicates.add(criteriaBuilder.equal(root.get("email"), employPO.getEmail()));
            }
            if (Objects.nonNull(employPO.getAge())) {
                predicates.add(criteriaBuilder.equal(root.get("age"), employPO.getAge()));
            }
            return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).
                    getRestriction();
        };
        final Page<EmployPO> employPOPage = this.getDao().findAll(spec, pageRequest);
        List<EmployPO> result = employPOPage.getContent();
        List<CommonVO> commonVOList = new ArrayList<>();
        for (EmployPO po : result) {
            Transfer<EmployPO> transfer = new Transfer<>();
            try {
                CommonVO commonVO = transfer.poToVo(po);
                commonVOList.add(commonVO);
            } catch (Exception exception) {
                throw new RuntimeException(exception);
            }
        }
        return new PageImpl<CommonVO>(commonVOList, pageRequest, employPOPage.getTotalElements());
    }
}
